package per.dg.keepalive.multiprocess.multiprocessmessenger

import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.os.*
import android.util.Log


class MultiProcessMessengerService : Service() {

    private val TAG : String = "Mul...MessengerService"

    override fun onBind(intent: Intent): IBinder {
        return mMessenger.binder
    }

    val mMessengerHandler : Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what){
                MESSAGE_FROM_CLIENT -> {
                    Log.e(TAG, "receive message from client:" + msg.getData().getString("msg"))
                    mMessengerClient = msg.replyTo

                    sendDataToClient(1)
                }
                else ->{
                    super.handleMessage(msg)
                }
            }
        }
    }

    val mMessenger : Messenger = Messenger(mMessengerHandler)

    lateinit var mMessengerClient : Messenger

    fun sendDataToClient(i : Int){


        val msg: Message = Message.obtain(null, MESSAGE_FROM_SERVICE)
        val bundle = Bundle()
        bundle.putString("msg", "hello client$i, I have received your message!")
        msg.data = bundle
        try {
            mMessengerClient.send(msg)
        } catch (e: RemoteException) {
            e.printStackTrace()
        }

    }

    fun startMainService(){
        val intent = Intent()
        val componentName =
            ComponentName("per.dg.keepalive", "com.lenovo.gemini.OOBE.MyService")
        intent.component = componentName
        startService(intent)
    }
}